//
//  WelcomeViewController.swift
//  SinaBlog
//
//  Created by ChenWei on 15/11/2.
//  Copyright © 2015年 cw. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class WelcomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.初始化界面
        setupUI()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 1.更新约束
        self.iconButton.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(-UIScreen.mainScreen().bounds.height + 160)
        }
        
        // 2.执行动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
               UIView.animateWithDuration(1.0, animations: { () -> Void in
                self.textLabel.alpha = 1.0
                }, completion: { (_) -> Void in
                    // 进入"首页界面"
                    NSLog(message: "欢迎回来动画执行完毕")
                    NSNotificationCenter.defaultCenter().postNotificationName(CWSwitchRootViewControllerNotify, object: nil)
               })
        }
    }
    
    // MARK:- 初始化界面
    private func setupUI() {
        // 1.添加子控件
        view.addSubview(bgImageView)
        view.addSubview(iconButton)
        view.addSubview(textLabel)
        
        // 2.布局子控件
        // 2.1背景图片
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(0)
        }
        // 2.2用户头像
        iconButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(0)
            make.bottom.equalTo(-160)
            make.size.equalTo(CGSizeMake(80, 80))
        }
        // 2.3"欢迎回来"Label
        textLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(0)
            make.top.equalTo(iconButton.snp_bottom).offset(10)
        }
    }
    
    // MARK:- 懒加载
    /// 1.背景图片
    private lazy var bgImageView : UIImageView = {
        let bgImageView = UIImageView()
        bgImageView.image = UIImage(named: "ad_background")
        return bgImageView
        }()
    
    /// 2.用户头像
    private lazy var iconButton : UIButton = {
        let iconButton = UIButton()
        let url = NSURL(string: (UserAccount.loadAccount()?.avatar_large)!)
        NSLog(message: url)
        iconButton.sd_setBackgroundImageWithURL(url, forState: UIControlState.Normal, placeholderImage: UIImage(named: "avatar_default_big"))
        
        iconButton.layer.cornerRadius = 40
        iconButton.clipsToBounds = true
        
        return iconButton
    }()
    
    /// 3.欢迎label
    private lazy var textLabel : UILabel = {
        let textLabel = UILabel()
        textLabel.text = "欢迎回来"
        textLabel.alpha = 0.0
        return textLabel
    }()
}
